<template>
  <base-breadcrumb :title="title" :breadcrumb="!isAudit">
    <!-- 质量创优预算编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 基本信息 -->
        <a-card :bordered="false" style="margin-bottom: 46px">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :isEmit="false" :form="form" :editModel="editModel == 0 ? 'V' : ''"
          @selectOrg="selectOrg">
          </custom-form>
          <title-name title="相关附件" />
          <BTableUpload v-model="form.fileArrays" :disabled="editModel == 0" business-code="QM11" />
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2 || editModel == 3"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >{{ statusCode === '2' || statusCode === '3' || form.version > 1 ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode === '0' || statusCode === '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode === '2')
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { excellenceBudget } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import Selector from '@/components/Select/Selector' // 项目名称

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增, 3调整
      id: '', // 业务id
      historyId: '', // 履历id
      form: {
        branchComId: '',
        fillerDate: '',
        filler: '',
        viewName: ""
      }, // 表单
      statusCode: '', // 审批状态
      rules: {
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        budgetMoney: [{ required: true, message: '请输入预算金额（万元）', trigger: 'change' }],
        targetId: [{ required: true, message: '请选择创优目标', trigger: 'change' }],
        name: [{ required: true, whitespace: true, message: '请输入文件名称', trigger: 'change' }],
        textPage: [{ required: true, message: '请输入正文页数', trigger: 'change' }],
        attachPage: [{ required: true, message: '请输入附页页数', trigger: 'change' }],
        budgetSketch: [{ required: true, message: '请输入预算简述', trigger: 'change' }]
      },
      titles: ['查看质量创优预算', '编辑质量创优预算', '新增质量创优预算', '调整质量创优预算'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      let args = {}
      if (this.businessId) {
        args.id = this.businessId
      } else {
        args.id = this.id
      }
      this.historyId && (args.historyId = this.historyId)
      excellenceBudget
        .getDetail(args)
        .then((res) => {
          this.loading[0] = false
          if (res.code === 200) {
            res.data.planTypeId = res.data.planType?.id // 映射方案类别id
            res.data.planTypeName = res.data.planType?.name // 映射方案类别name
            // 若文件不存在则设置空数组
            !res.data.fileArrays && (res.data.fileArrays = [])
            this.form = res.data
            this.form.viewName = this.form.branchComName + '/' + this.form.projectName
            this.statusCode = res.data.statusCode // 审批状态
            this.$nextTick(() => {
              if (this.editModel != 0) {
                this.form.filler = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
                this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
              }
              res.data.editorEmployeeId &&
                res.data.editor &&
                this.$set(this.form, 'editorEmployee', {
                  key: res.data.editorEmployeeId,
                  label: res.data.editor
                })
            })
          }
        })
        .catch(() => {
          this.loading[0] = false
        })
    } else {
      this.form.filler = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
      this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_create_excellence_budget')
  },
  computed: {
    // 表单列表
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          disabled: this.editModel != 2,
          isNoBorder: this.editModel == 0,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   viewName: 'branchComName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'budgetMoney',
          type: 'BaseInputNumber',
          precision: 6,
          label: '预算金额（万元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'settlementMoney',
          type: 'BaseInputNumber',
          precision: 6,
          label: '结算金额（万元）',
          attrs: {
            min: 0
          }
        },
        {
          label: '创优目标',
          type: Selector,
          keyName: 'targetId',
          viewName: 'targetName',
          attrs: {
            selectType: '52'
          }
        },
        {
          label: '文件名称',
          type: 'BaseInput',
          keyName: 'name'
        },
        {
          keyName: 'textPage',
          type: 'BaseInputNumber',
          label: '正文页数',
          precision: 0,
          attrs: {
            min: 1
          }
        },
        {
          keyName: 'attachPage',
          type: 'BaseInputNumber',
          label: '附页页数',
          precision: 0,
          attrs: {
            min: 1
          }
        },
        {
          keyName: 'filler',
          type: 'a-input',
          disabled: true,
          label: '创建人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-date-picker',
          disabled: true,
          label: '创建时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'budgetSketch',
          label: '预算简述',
          type: 'BaseTextarea',
          autoSize: { minRows: 10, maxRows: 10 },
          attrs: {
            maxLength: 3000
          },
          ellipsis: true,
          span: 24
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null;
      let name = ['updatePost', 'create', 'adjustment'][that.editModel - 1] // 根据操作切换url地址
      const submit = () => {
        // 提交表单
        that.loading[statusCode] = true
        let form = that.$clone(that.form)
        form.statusCode = that.statusCode == '3' && statusCode == 0 ? that.statusCode : statusCode
        form.editorEmployee && delete form.editorEmployee
        excellenceBudget[name](form)
          .then((res) => {
            if (res.code === 200 || res.data.code === 200) {
              that.loading[statusCode] = false
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
              if(statusCode*1===1) {
            //提交时，返回id
                that.businessId = res.data.id;
                that.setProcessConfig = this.processConfig;
                return
             }else{
              that.$multiTab.close()
              }
            }
          })
          .catch(() => {
            that.loading[statusCode] = false
          })
      }
      // 若是草稿则无需校验表单
      if (statusCode === 0) {
        submit()
        return
      }
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          if(!that.form.fileArrays?.length){
            that.$message.warning('附件不能为空！')
            return
          }
          this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              return
            }
            submit()
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
